package com.xo.user.config;

import com.xo.common.pojo.entity.SysUserEntity;
import com.xo.common.until.ExceptionUtil;
import com.xo.user.controller.LoginUser;
import com.xo.user.mapper.LoginMapper;
import com.xo.user.until.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

@Slf4j
@Component
public class TokenFilter extends OncePerRequestFilter {

    @Resource
    private LoginMapper loginMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 获取 JWT
        String token = request.getHeader("Authorization");

        if (!(StringUtils.hasText(token) && token.startsWith("Bearer "))) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("token无效");
            return;
        }

        token = token.substring(7); // 去掉 "Bearer " 前缀

        //解析 JWT
        Long tenantId = null;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            tenantId = Long.valueOf(claims.getSubject());
        } catch (Exception e) {
            ExceptionUtil.throwException("token解析失败");
        }

        //根据tenantId
        SysUserEntity sysUserEntity = loginMapper.selectCountByTenantId(tenantId);

        if (Objects.isNull(sysUserEntity)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("用户名未登录");
            return;
        }

        //置安全上下文
        LoginUser loginUser = new LoginUser(sysUserEntity.getUsername(),sysUserEntity.getPassword(), null, tenantId);
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, null);

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);


        filterChain.doFilter(request, response);
    }
}
